package com.myblog.config;

import com.myblog.service.impl.UserDetailServiceImpl;
import com.myblog.utils.MD5Util;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @Date: 2022/6/5 18:45
 * Describe: SpringSecurity配置
 */
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    //定义用户信息服务（查询用户
    @Bean
    UserDetailsService userDetailServiceImpl(){
        return new UserDetailServiceImpl();
    }


    //定义密码编码器
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailServiceImpl()).passwordEncoder(new PasswordEncoder() {
            MD5Util md5Util = new MD5Util();
            @Override
            public String encode(CharSequence rawPassword) {
                return md5Util.encode((String) rawPassword);
            }

            @Override
            public boolean matches(CharSequence rawPassword, String encodedPassword) {
                return encodedPassword.equals(md5Util.encode((String) rawPassword));
            }
        });
    }


    //配置安全拦截机制（重要的）
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http
            .authorizeRequests()
            .antMatchers("/","/index","/aboutme","/archives","/categories","/friendlylink","/tags","/update")
                .permitAll()
                .antMatchers("/editor","/user").hasAnyRole("USER")//拥有user角色权限访问
                .antMatchers("/ali","/mylove").hasAnyRole("ADMIN")//拥有admin角色权限访问
                .antMatchers("/superadmin","/myheart","/today","/yesterday").hasAnyRole("SUPERADMIN")//拥有superadmin角色权限访问
                .and()
                //formLogin允许表单登录，loginPage跳转到自定义登录界面，failureUrl失败后跳转，defaultSuccessUrl成功后跳转，也可以使用successForwardUrl("/")
                .formLogin().loginPage("/login").failureUrl("/login?error").defaultSuccessUrl("/")
                .and()
                .headers().frameOptions().sameOrigin()//通过引用页面/iframe/frame，通过此语句实现
                .and()
//                .sessionManagement()
//                .maximumSessions(1)
//                .maxSessionsPreventsLogin(false)
//                .and()
//                .and()
                .logout().logoutUrl("/logout").logoutSuccessUrl("/");


        //解除csrf屏蔽
        http.csrf().disable();
    }
}
